package com.whiteape.book.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.view.KeyEvent;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;

import com.gyf.immersionbar.ImmersionBar;
import com.hwangjr.rxbus.RxBus;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.whiteape.book.R;
import com.whiteape.book.common.RxEvent;
import com.whiteape.book.contract.MainContract;
import com.whiteape.book.core.manager.ReadSettingManager;
import com.whiteape.book.core.manager.SiteSourceManager;
import com.whiteape.book.core.page.PageMode;
import com.whiteape.book.presenter.MainPresenter;
import com.whiteape.book.ui.base.BaseFragment;
import com.whiteape.book.ui.base.BaseTabNavigaterActivity;
import com.whiteape.book.ui.dialog.BookReadSettingDialog;
import com.whiteape.book.ui.fragment.DiscoveryFragment;
import com.whiteape.book.ui.fragment.HomepageFragment;
import com.whiteape.book.ui.fragment.SiteCategoryFragment;
import com.whiteape.book.ui.fragment.MediaCollectionFragment;
import com.whiteape.book.ui.fragment.MineFragment;
import com.whiteape.book.ui.fragment.RecommendFragment;
import com.whiteape.book.ui.fragment.SiteSourceFragment;
import com.whiteape.book.utils.AppUtils;
import com.whiteape.book.utils.FileUtils;
import com.whiteape.book.utils.RxUtils;
import com.whiteape.book.utils.ScreenUtils;
import com.whiteape.book.utils.ShareUtil;
import com.whiteape.book.utils.ToastUtils;
import com.whiteape.book.utils.textview.CustomMovementMethod;
import com.whiteape.book.utils.textview.CustomURLSpan;

import io.reactivex.disposables.Disposable;

public class MainActivity extends BaseTabNavigaterActivity<MainContract.Presenter> implements MainContract.View, UMShareListener {

//    @BindView(R.id.card_search)
//    CardView mCardView;


    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
    }

    @Override
    protected void initView() {

//        ImmersionBar.with(this)
//                .fitsSystemWindows(true)  //使用该属性,必须指定状态栏颜色
//                .statusBarColor(R.color.white)
//                .init();
        super.initView();
//        ImmersionBar.with(this)
//                .fitsSystemWindows(true)  //使用该属性,必须指定状态栏颜色
//                .statusBarColor(R.color.colorAccent)
//                .init();
//        ImmersionBar.with(this).statusBarDarkFont(true).init();
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        if (getCurrentFragment() == null || (getCurrentFragment() instanceof HomepageFragment)
        || (getCurrentFragment() instanceof DiscoveryFragment)) {
            ImmersionBar.with(this)
                    .fitsSystemWindows(true)  //使用该属性,必须指定状态栏颜色
                    .statusBarDarkFont(false)
                    .statusBarColor(R.color.colorAccent)
                    .init();

        } else {

            ImmersionBar.with(this)
                    .fitsSystemWindows(true)  //使用该属性,必须指定状态栏颜色
                    .statusBarDarkFont(true)
                    .statusBarColor(R.color.colorPrimary)
                    .init();
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
//        mCardView.setOnClickListener(v -> startActivity(new Intent(MainActivity.this, SearchActivity.class)));
        tabContainerView.setOnTabSelectedListener(tab -> {
            initImmersionBar();
        });

    }

    @Override
    protected void startLogic() {
        super.startLogic();
//        com.whiteape.book.MainActivity.importSource();
//        testTTS();
//        WechatUtils.jumpToWechatOffcialAccount(this);
        importSource();
        checkIfAgreedProtocol();

    }

    private void initPermission() {
        RxPermissions rxPermissions = new RxPermissions(this);
        if (!rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            new AlertDialog.Builder(this)
                    .setTitle(R.string.wa_common_tip)
                    .setMessage(R.string.permission_request_sdcard_init)
                    .setPositiveButton(R.string.wa_common_sure, ((dialogInterface, i) -> {
                        dialogInterface.dismiss();
//                        rxPermissionRequest(rxPermissions, fragment, listener);
                        String permissionRequired = Manifest.permission.WRITE_EXTERNAL_STORAGE;
                        Disposable disposable = rxPermissions.requestEach(permissionRequired)
                                .subscribe(permission -> {

                                });
                        addDisposable(disposable);
                    })).show();
        }
    }

    private void importSource() {
        int lastImportSourceVersionCode = ReadSettingManager.getInstance().getSiteSourceVersionCode();
        int versionCode = AppUtils.getVersionCode(this);
        if (lastImportSourceVersionCode < versionCode) {
            ReadSettingManager.getInstance().setPageMode(PageMode.COVER);
            //判断当前版本是不是导入过了
            addDisposable(SiteSourceManager.getInstance()
                    .importSiteSource(FileUtils.getJsonFromAssets(this, "all.was"))
                    .compose(RxUtils::toSimpleSingle)
                    .subscribe(integer -> {

                        RxBus.get().post(RxEvent.SITE_SOURCE_ADDED);
                        ReadSettingManager.getInstance().setSiteSourceVersionCode(versionCode);
                            }
                    ));
        }
    }

    //检测是否是第一次打开，是的话，要弹出免责声明
    private void checkIfAgreedProtocol() {
        boolean agreed = ReadSettingManager.getInstance().getIfAgreedProtocol();
        if (!agreed) {
            ReadSettingManager.getInstance().setAutoBrightness(true);
            TextView tvProtocol = new TextView(this);
            tvProtocol.setPadding(ScreenUtils.dpToPx(15), ScreenUtils.dpToPx(35), ScreenUtils.dpToPx(15), ScreenUtils.dpToPx(35));
            tvProtocol.setTextSize(18);

            SpannableString ss = new SpannableString(getResources().getString(R.string.init_protocol));
            ss.setSpan(new CustomURLSpan("http://privacy"), 21, 25,
                    Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            ss.setSpan(new CustomURLSpan("http://disclaimer"), 27, 31,
                    Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            tvProtocol.setText(ss);
            tvProtocol.setMovementMethod(new CustomMovementMethod(this));
            new AlertDialog.Builder(this)
                    .setTitle("欢迎使用")
                    .setView(tvProtocol)
                    .setNeutralButton(R.string.wa_common_not_agree, (dialog, which) -> {
                        dialog.dismiss();
                        finish();
                    })
                    .setPositiveButton(R.string.wa_common_agree, ((dialog, which) -> {
                        dialog.dismiss();
                        ReadSettingManager.getInstance().setIfAgreedProtocol(true);
                        initPermission();
                    })).show();
        }


    }

    private void testTTS() {
//        SpeechSynthesizer mTTSPlayer = new SpeechSynthesizer(this, WaConstants.YZS_APPKEY, WaConstants.YZS_SECRET);
//        mTTSPlayer.setOption(SpeechConstants.TTS_SERVICE_MODE, SpeechConstants.TTS_SERVICE_MODE_LOCAL);
//        mTTSPlayer.setTTSListener(new SpeechSynthesizerListener() {
//            @Override
//            public void onEvent(int i) {
//
//            }
//
//            @Override
//            public void onError(int i, String s) {
//
//            }
//        });
//        mTTSPlayer.init(null);
//        mTTSPlayer.playText("哈哈哈我可以播放语音啦");
    }

    @Override
    protected void setUpToolbar(Toolbar toolbar) {
        super.setUpToolbar(toolbar);
//        toolbar.setLogo(R.mipmap.logo);
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        getSupportActionBar().setTitle("");
    }

    @Override
    protected Fragment[] createTabFragments() {
        MediaCollectionFragment mediaCollectionFragment = null;
        SiteSourceFragment siteSourceFragment = null;
        MineFragment mineFragment = null;
        RecommendFragment recommendFragment = null;
//        SiteCategoryFragment siteCategoryFragment = null;
        HomepageFragment homepageFragment = null;

        SiteCategoryFragment siteCategoryFragment = null;
        DiscoveryFragment discoveryFragment = null;

        for (Fragment fragment : getSupportFragmentManager().getFragments()) {
            if (fragment instanceof MediaCollectionFragment) {
                mediaCollectionFragment = (MediaCollectionFragment) fragment;
//            } else if (fragment instanceof SiteCategoryFragment) {
//                siteCategoryFragment = (SiteCategoryFragment) fragment;
            } else if (fragment instanceof SiteSourceFragment) {
                siteSourceFragment = (SiteSourceFragment) fragment;
            } else if (fragment instanceof MineFragment) {
                mineFragment = (MineFragment) fragment;
            } else if (fragment instanceof RecommendFragment) {
                recommendFragment = (RecommendFragment) fragment;
            } else if (fragment instanceof SiteCategoryFragment) {
                siteCategoryFragment = (SiteCategoryFragment) fragment;
            } else if (fragment instanceof HomepageFragment) {
                homepageFragment = (HomepageFragment) fragment;
            } else if (fragment instanceof DiscoveryFragment) {
                discoveryFragment = (DiscoveryFragment)fragment;
            }
        }
        if (mediaCollectionFragment == null) {
            mediaCollectionFragment = new MediaCollectionFragment();
        }
//        if (siteCategoryFragment == null) {
//            siteCategoryFragment = new SiteCategoryFragment();
//        }
        if (siteSourceFragment == null) {
            siteSourceFragment = new SiteSourceFragment();
        }
        if (mineFragment == null) {
            mineFragment = new MineFragment();
        }
        if (recommendFragment == null) {
            recommendFragment = new RecommendFragment();
        }
        if (siteCategoryFragment == null) {
            siteCategoryFragment = new SiteCategoryFragment();
        }

        if (homepageFragment == null) {
            homepageFragment = new HomepageFragment();
        }
        if (discoveryFragment == null) {
            discoveryFragment = new DiscoveryFragment();
        }
        return new Fragment[]{homepageFragment,/**recommendFragment, */mediaCollectionFragment, discoveryFragment,/*siteSourceFragment, siteCategoryFragment,*/ mineFragment};
    }

    @Override
    protected String[] createTitleArray() {
//        return new String[]{"首页", "书架", "网源", "分类", "我的"};
        return new String[]{"首页", "书架", "发现", "我的"};
//        return getResources().getStringArray(R.array.home_tab_name);
    }

    @Override
    protected int[] createIconNormalArray() {
//        return new int[]{R.mipmap.home_recommend_new,/**R.mipmap.home_recommend_new, */R.mipmap.home_bookshelf_new, R.mipmap.home_source, R.mipmap.home_category, R.mipmap.home_mine};
        return new int[]{R.mipmap.home_recommend_new,/**R.mipmap.home_recommend_new, */R.mipmap.home_bookshelf_new, R.mipmap.home_find_new, R.mipmap.home_mine};
    }

    @Override
    protected int[] createIconSelectedArray() {
//        return new int[]{R.mipmap.home_recommend_new,/**R.mipmap.home_recommend_new,*/R.mipmap.home_bookshelf_new, R.mipmap.home_source, R.mipmap.home_category, R.mipmap.home_mine};
        return new int[]{R.mipmap.home_recommend_new,/**R.mipmap.home_recommend_new, */R.mipmap.home_bookshelf_new, R.mipmap.home_find_new, R.mipmap.home_mine};
    }

    @Override
    protected MainContract.Presenter bindPresenter() {
        return new MainPresenter();
    }

    @Override
    protected int getContentId() {
        return R.layout.activity_main;
    }


    @Override
    public void onRestore(String msg) {

    }

    @Override
    public void showError() {

    }

    @Override
    public void complete() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    // 用来计算返回键的点击间隔时间
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        Fragment currentFragment = getCurrentFragment();
        if (currentFragment instanceof BaseFragment) {
            if (((BaseFragment) currentFragment).onKeyDown(keyCode, event)) {
                return true;
            } else {
                if (keyCode == KeyEvent.KEYCODE_BACK
                        && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if ((System.currentTimeMillis() - exitTime) > 2000) {
                        //弹出提示，可以有多种方式
                        Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                        exitTime = System.currentTimeMillis();
                    } else {
                        finish();
                    }
                    return true;
                }

            }
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onStart(SHARE_MEDIA share_media) {

    }

    @Override
    public void onResult(SHARE_MEDIA share_media) {

//        toast(getResources().getString(R.string.share_success));
        ShareUtil.recordNewShareTime();

    }

    @Override
    public void onError(SHARE_MEDIA share_media, Throwable throwable) {
        ToastUtils.show(getResources().getString(R.string.share_error));

    }

    @Override
    public void onCancel(SHARE_MEDIA share_media) {
        ToastUtils.show(getResources().getString(R.string.share_cancel));

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }


    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        initImmersionBar();
    }
}
